// BOSS游戏主逻辑
class BossGame {
    constructor() {
        this.canvas = document.getElementById('bossGameCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        // 游戏状态
        this.gameState = {
            isRunning: false,
            isPaused: false,
            score: 0,
            playerHealth: 100,
            playerLength: 5, // 初始长度设为5
            inventory: [],
            foods: [], // 添加食物数组
            items: [] // 添加物品数组
        };
        
        // 玩家属性
        this.player = {
            x: 400,
            y: 300,
            width: 20,
            height: 20,
            speed: 2, // 降低默认速度
            direction: 'right',
            body: []
        };
        
        // 按键状态
        this.keys = {
            w: false,
            a: false,
            s: false,
            d: false,
            arrowup: false,
            arrowleft: false,
            arrowdown: false,
            arrowright: false,
            f: false
        };
        
        // 游戏区域尺寸
        this.gameWidth = 800;
        this.gameHeight = 600;
        
        // 帧率控制
        this.lastUpdateTime = 0;
        this.updateInterval = 100; // 每100毫秒更新一次，提高响应速度
        
        // BOSS属性 - 岩石巨蟒
        this.boss = {
            name: '岩石巨蟒',
            health: 1000,
            maxHealth: 1000,
            attackPower: 20,
            x: 600,
            y: 200,
            width: 40, // 2x2格子的BOSS（每个格子20px，2x2=40px）
            height: 40,
            direction: 'left',
            speed: 1,
            body: [],
            isShieldActive: false,
            shieldDuration: 0,
            isWeak: false, // 虚弱状态
            weakDuration: 0,
            attacks: [], // 初始化攻击数组
            lastHeadCollisionTime: 0 // 上次头部碰撞时间，用于冷却时间控制
        };
        
        this.init();
    }
    
    init() {
        // 设置画布尺寸
        this.canvas.width = this.gameWidth;
        this.canvas.height = this.gameHeight;
        
        // 初始化玩家身体
        this.initPlayerBody();
        
        // 初始化BOSS身体
        this.initBossBody();
        
        // 设置事件监听器
        this.setupEventListeners();
        
        // 开始游戏循环
        this.startGame();
        
        // 定时生成食物
        setInterval(() => {
            if (this.gameState.isRunning && !this.gameState.isPaused) {
                this.generateFood();
            }
        }, 3000); // 每3秒生成一次食物
        
        // 定时生成物品
        setInterval(() => {
            if (this.gameState.isRunning && !this.gameState.isPaused) {
                this.generateItem();
            }
        }, 5000); // 每5秒生成一次物品
    }
    
    initPlayerBody() {
        this.player.body = [];
        const gridSize = 20; // 网格大小
        
        // 确保玩家初始位置与网格对齐
        const alignedX = Math.floor(this.player.x / gridSize) * gridSize;
        const alignedY = Math.floor(this.player.y / gridSize) * gridSize;
        
        for (let i = 0; i < this.gameState.playerLength; i++) {
            this.player.body.push({
                x: alignedX - i * gridSize, // 按照网格系统向左延伸
                y: alignedY,
                width: this.player.width,
                height: this.player.height
            });
        }
        
        // 确保身体段不会重叠
        console.log('初始化身体段:', this.player.body);
    }
    
    initBossBody() {
        this.boss.body = [];
        const gridSize = 20; // 网格大小
        
        // 岩石巨蟒的身体由7个段组成，每个段都是4个格子（2x2）
        const bossLength = 7; // BOSS身体长度改为7块
        
        for (let i = 0; i < bossLength; i++) {
            this.boss.body.push({
                x: this.boss.x + i * gridSize, // 向右延伸
                y: this.boss.y,
                width: this.boss.width,  // 40px = 2x2格子
                height: this.boss.height // 40px = 2x2格子
            });
        }
        
        console.log('初始化BOSS身体段:', this.boss.body);
    }
    
    setupEventListeners() {
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            const key = e.key.toLowerCase();
            
            // 暂停/继续游戏
            if (key === 'escape') {
                this.togglePause();
                return;
            }
            
            // 更新按键状态
            if (key in this.keys) {
                this.keys[key] = true;
            }
            
            // 防止页面滚动
            if (['w', 'a', 's', 'd', 'arrowup', 'arrowleft', 'arrowdown', 'arrowright', 'f'].includes(key)) {
                e.preventDefault();
            }
        });
        
        document.addEventListener('keyup', (e) => {
            const key = e.key.toLowerCase();
            if (key in this.keys) {
                this.keys[key] = false;
            }
        });
        
        // 窗口大小变化事件
        window.addEventListener('resize', () => {
            this.handleResize();
        });
        
        // 控制按钮事件
        this.setupControlButtons();
    }
    
    setupControlButtons() {
        const pauseBtn = document.getElementById('pauseBtn');
        const restartBtn = document.getElementById('restartBtn');
        const resumeBtn = document.getElementById('resumeBtn');
        const backBtn = document.getElementById('backBtn');
        
        if (pauseBtn) {
            pauseBtn.addEventListener('click', () => this.togglePause());
        }
        
        // 取消重新开始按钮功能
        // if (restartBtn) {
        //     restartBtn.addEventListener('click', () => this.restartGame());
        // }
        
        if (resumeBtn) {
            resumeBtn.addEventListener('click', () => this.togglePause());
        }
        
        if (backBtn) {
            backBtn.addEventListener('click', () => this.backToMenu());
        }
    }
    
    handleResize() {
        // 保持游戏区域比例，防止滚动
        const gameArea = document.querySelector('.game-canvas-container');
        if (gameArea) {
            const containerWidth = gameArea.clientWidth;
            const containerHeight = gameArea.clientHeight;
            
            // 计算缩放比例
            const scaleX = containerWidth / this.gameWidth;
            const scaleY = containerHeight / this.gameHeight;
            const scale = Math.min(scaleX, scaleY, 1);
            
            this.canvas.style.width = (this.gameWidth * scale) + 'px';
            this.canvas.style.height = (this.gameHeight * scale) + 'px';
        }
    }
    
    startGame() {
        this.gameState.isRunning = true;
        this.gameLoop();
        this.updateUI();
    }
    
    gameLoop() {
        if (!this.gameState.isRunning || this.gameState.isPaused) {
            return;
        }
        
        const currentTime = Date.now();
        
        // 帧率控制：只有当时间间隔超过设定值时才更新游戏逻辑
        if (currentTime - this.lastUpdateTime >= this.updateInterval) {
            this.update();
            this.lastUpdateTime = currentTime;
        }
        
        // 渲染不受帧率控制，保持流畅
        this.render();
        
        requestAnimationFrame(() => this.gameLoop());
    }
    
    update() {
        this.handleInput();
        this.updatePlayer();
        this.updateBoss();
        this.updateAttacks();
        this.checkBoundaries();
        this.checkCollisions();
        this.checkFoodCollisions(); // 检查食物碰撞
        this.checkItemCollisions(); // 检查物品碰撞
        this.updateDamageEffects(); // 更新扣血特效
    }
    
    handleInput() {
        // 方向键控制 - 防止直接掉头
        if ((this.keys.w || this.keys.arrowup) && this.player.direction !== 'down') {
            this.player.direction = 'up';
        } else if ((this.keys.s || this.keys.arrowdown) && this.player.direction !== 'up') {
            this.player.direction = 'down';
        } else if ((this.keys.a || this.keys.arrowleft) && this.player.direction !== 'right') {
            this.player.direction = 'left';
        } else if ((this.keys.d || this.keys.arrowright) && this.player.direction !== 'left') {
            this.player.direction = 'right';
        }
        
        // F键放置陷阱
        if (this.keys.f) {
            this.placeTrap();
            this.keys.f = false; // 重置按键状态
        }
    }
    
    updatePlayer() {
        const gridSize = 20; // 网格大小
        
        // 移动头部 - 按照网格系统移动
        const head = { ...this.player.body[0] };
        
        switch (this.player.direction) {
            case 'up':
                head.y -= gridSize; // 每次移动一个网格
                break;
            case 'down':
                head.y += gridSize;
                break;
            case 'left':
                head.x -= gridSize;
                break;
            case 'right':
                head.x += gridSize;
                break;
        }
        
        // 更新身体位置
        this.player.body.unshift(head);
        if (this.player.body.length > this.gameState.playerLength) {
            this.player.body.pop();
        }
        
        // 更新玩家位置
        this.player.x = head.x;
        this.player.y = head.y;
    }
    
    playerAttack() {
        // 玩家攻击逻辑（后续添加）
        console.log('玩家攻击！');
        
        // 更新UI显示攻击状态
        this.updateAttackStatus();
    }
    
    placeTrap() {
        // 放置陷阱逻辑
        // 检查物品栏中是否有陷阱
        const trapIndex = this.gameState.inventory.findIndex(item => item.effect === 'trap');
        
        if (trapIndex !== -1) {
            // 检查陷阱数量限制：全场最多同时存在3个
            if (!this.gameState.placedTraps) {
                this.gameState.placedTraps = [];
            }
            
            if (this.gameState.placedTraps.length >= 3) {
                this.showStatusMessage('陷阱数量已达上限（3个）！');
                return;
            }
            
            const trap = this.gameState.inventory[trapIndex];
            
            // 在玩家当前位置放置陷阱
            const placedTrap = {
                x: this.player.x,
                y: this.player.y,
                width: 20,
                height: 20,
                name: '陷阱',
                color: '#ff0000', // 改为红色
                effect: 'trap',
                placed: true,
                placedTime: Date.now(),
                duration: 10000 // 10秒后消失
            };
            
            // 添加到已放置陷阱数组
            this.gameState.placedTraps.push(placedTrap);
            
            // 从物品栏移除陷阱
            this.removeItemFromInventory(trapIndex);
            
            // 设置陷阱消失定时器
            setTimeout(() => {
                if (this.gameState.placedTraps) {
                    const index = this.gameState.placedTraps.indexOf(placedTrap);
                    if (index !== -1) {
                        this.gameState.placedTraps.splice(index, 1);
                        console.log('陷阱消失');
                    }
                }
            }, placedTrap.duration);
            
            this.showStatusMessage('陷阱已放置！');
            console.log('陷阱已放置在位置:', placedTrap.x, placedTrap.y);
        } else {
            this.showStatusMessage('物品栏中没有陷阱');
        }
    }
    
    updateBoss() {
        const gridSize = 20; // 网格大小
        
        // 岩石巨蟒绕着地图边缘移动
        // 由于每个BOSS段是2x2格子（40px），移动步长需要是2个格子
        switch (this.boss.direction) {
            case 'left':
                this.boss.x -= gridSize * 2 * this.boss.speed; // 每次移动2个格子
                if (this.boss.x <= 0) {
                    this.boss.direction = 'up';
                    this.boss.x = 0;
                }
                break;
            case 'up':
                this.boss.y -= gridSize * 2 * this.boss.speed; // 每次移动2个格子
                if (this.boss.y <= 0) {
                    this.boss.direction = 'right';
                    this.boss.y = 0;
                }
                break;
            case 'right':
                this.boss.x += gridSize * 2 * this.boss.speed; // 每次移动2个格子
                if (this.boss.x + this.boss.width >= this.gameWidth) {
                    this.boss.direction = 'down';
                    this.boss.x = this.gameWidth - this.boss.width;
                }
                break;
            case 'down':
                this.boss.y += gridSize * 2 * this.boss.speed; // 每次移动2个格子
                if (this.boss.y + this.boss.height >= this.gameHeight) {
                    this.boss.direction = 'left';
                    this.boss.y = this.gameHeight - this.boss.height;
                }
                break;
        }
        
        // 更新BOSS身体位置
        this.updateBossBody();
        
        // 执行BOSS攻击
        this.bossAttack();
    }
    
    updateBossBody() {
        const gridSize = 20;
        
        // 类似贪吃蛇的身体跟随逻辑，而不是整体偏移
        // 首先将头部位置添加到身体数组开头
        this.boss.body.unshift({
            x: this.boss.x,
            y: this.boss.y,
            width: this.boss.width,  // 40px = 2x2格子
            height: this.boss.height // 40px = 2x2格子
        });
        
        // 保持身体长度为7块
        if (this.boss.body.length > 7) {
            this.boss.body.pop();
        }
    }
    
    bossAttack() {
        // BOSS攻击逻辑
        // 确保BOSS对象已正确初始化
        if (!this.boss || !this.boss.attacks) {
            console.warn('BOSS对象未正确初始化，无法执行攻击');
            return;
        }
        
        // 基础攻击：向玩家方向丢石头
        if (Math.random() < 0.02) { // 2%概率触发基础攻击
            this.throwRock();
        }
        
        // 高级攻击：大石头从蛇头飞向玩家位置
        if (Math.random() < 0.005) { // 0.5%概率触发高级攻击
            // 警告开始时定位玩家坐标
            const targetX = this.player.x;
            const targetY = this.player.y;
            
            this.showAttackWarning('巨石攻击', 2000); // 2秒预警
            
            // 2秒后从蛇头飞向指定位置（过程0.5秒）
            setTimeout(() => {
                this.throwBigRock(targetX, targetY);
            }, 2000);
        }
        
        // 特殊能力：周期性释放岩石护盾
        if (Math.random() < 0.01) { // 1%概率触发护盾
            this.activateRockShield();
        }
    }
    
    throwRock() {
        // 确保BOSS对象已正确初始化
        if (!this.boss || !this.boss.attacks) {
            console.warn('BOSS对象未正确初始化，无法执行投石攻击');
            return;
        }
        
        // 基础攻击：向玩家方向丢石头
        console.log('岩石巨蟒丢石头攻击！');
        
        // 创建石头攻击对象
        const rock = {
            x: this.boss.x,
            y: this.boss.y,
            width: 20,
            height: 20,
            speed: 80, // 调整移动速度到80，使石头在5秒内刚好到达边界
            direction: this.getDirectionToPlayer(),
            damage: 20,
            createdTime: Date.now(), // 添加创建时间
            duration: 5000, // 5秒后消失
            moving: false // 普通石头直接按方向移动，不飞向目标位置
        };
        
        // 添加到攻击数组
        this.boss.attacks.push(rock);
    }
    
    throwBigRock(targetX, targetY) {
        // 确保BOSS对象已正确初始化
        if (!this.boss || !this.boss.attacks) {
            console.warn('BOSS对象未正确初始化，无法执行巨石攻击');
            return;
        }
        
        // 高级攻击：大石头从蛇头飞向玩家位置，0.5秒过程
        console.log('岩石巨蟒释放巨石攻击！');
        
        // 起始位置：蛇头位置
        const startX = this.boss.x;
        const startY = this.boss.y;
        
        // 计算移动距离和速度（0.5秒到达）
        const distanceX = targetX - startX;
        const distanceY = targetY - startY;
        const distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
        const speed = distance / 0.5; // 0.5秒到达的速度
        
        const bigRock = {
            x: startX,
            y: startY,
            width: 60,
            height: 60,
            speed: speed,
            targetX: targetX,
            targetY: targetY,
            moving: true, // 标记为移动状态
            damage: 50,
            createdTime: Date.now(), // 添加创建时间
            duration: 3000 // 3秒后消失
        };
        
        this.boss.attacks.push(bigRock);
    }
    
    activateRockShield() {
        // 确保BOSS对象已正确初始化
        if (!this.boss) {
            console.warn('BOSS对象未正确初始化，无法激活岩石护盾');
            return;
        }
        
        // 特殊能力：释放岩石护盾
        console.log('岩石巨蟒激活岩石护盾！');
        
        this.boss.shieldActive = true;
        this.boss.shieldDuration = 5000; // 5秒护盾
        
        // 5秒后护盾消失
        setTimeout(() => {
            if (this.boss) {
                this.boss.shieldActive = false;
                console.log('岩石护盾消失！');
            }
        }, 5000);
    }
    
    getDirectionToPlayer() {
        // 计算从BOSS到玩家的方向
        const dx = this.player.x - this.boss.x;
        const dy = this.player.y - this.boss.y;
        
        // 根据差值确定主要方向
        if (Math.abs(dx) > Math.abs(dy)) {
            return dx > 0 ? 'right' : 'left';
        } else {
            return dy > 0 ? 'down' : 'up';
        }
    }
    
    showAttackWarning(attackName, duration) {
        // 显示攻击预警
        if (!this.gameState.attackWarnings) {
            this.gameState.attackWarnings = [];
        }
        
        const warning = {
            name: attackName,
            startTime: Date.now(),
            duration: duration,
            active: true
        };
        
        this.gameState.attackWarnings.push(warning);
        
        // 显示状态消息
        this.showStatusMessage(`警告：${attackName}即将发动！`);
        
        // 预警结束后移除
        setTimeout(() => {
            if (this.gameState.attackWarnings) {
                const index = this.gameState.attackWarnings.indexOf(warning);
                if (index !== -1) {
                    this.gameState.attackWarnings.splice(index, 1);
                }
            }
        }, duration);
    }
    
    updateAttacks() {
        // 更新所有攻击对象的位置
        if (!this.boss.attacks) return;
        
        const currentTime = Date.now();
        
        for (let i = this.boss.attacks.length - 1; i >= 0; i--) {
            const attack = this.boss.attacks[i];
            
            // 检查攻击是否超过持续时间
            if (attack.createdTime && attack.duration) {
                const elapsed = currentTime - attack.createdTime;
                if (elapsed >= attack.duration) {
                    this.boss.attacks.splice(i, 1);
                    continue;
                }
            }
            
            // 处理移动攻击（从蛇头飞向玩家位置）
            if (attack.moving) {
                // 计算移动方向向量
                const dx = attack.targetX - attack.x;
                const dy = attack.targetY - attack.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                // 如果已经到达目标位置或距离很小
                if (distance <= attack.speed * 0.1) { // 一帧的距离（基于10FPS）
                    attack.x = attack.targetX;
                    attack.y = attack.targetY;
                    attack.moving = false;
                    
                    // 巨石攻击到达后继续向玩家方向移动
                    if (attack.width === 60) { // 巨石攻击
                        attack.direction = this.getDirectionToPlayer();
                        attack.speed = 3; // 降低移动速度
                    }
                } else {
                    // 向目标位置移动
                    const moveX = (dx / distance) * attack.speed * 0.1; // 每帧移动距离（基于10FPS）
                    const moveY = (dy / distance) * attack.speed * 0.1;
                    
                    attack.x += moveX;
                    attack.y += moveY;
                }
            } else {
                // 根据方向移动攻击
                if (attack.direction) {
                    switch (attack.direction) {
                        case 'left': attack.x -= attack.speed * 0.1; break; // 基于10FPS
                        case 'right': attack.x += attack.speed * 0.1; break;
                        case 'up': attack.y -= attack.speed * 0.1; break;
                        case 'down': attack.y += attack.speed * 0.1; break;
                    }
                }
            }
            
            // 检查攻击是否超出边界
            if (attack.x < -attack.width || attack.x > this.gameWidth ||
                attack.y < -attack.height || attack.y > this.gameHeight) {
                this.boss.attacks.splice(i, 1);
            }
        }
    }
    
    checkCollisions() {
        // 检查玩家与BOSS攻击的碰撞
        if (!this.boss.attacks) return;
        
        const playerHead = this.player.body[0];
        
        for (let i = this.boss.attacks.length - 1; i >= 0; i--) {
            const attack = this.boss.attacks[i];
            
            // 简单的矩形碰撞检测
            if (playerHead.x < attack.x + attack.width &&
                playerHead.x + playerHead.width > attack.x &&
                playerHead.y < attack.y + attack.height &&
                playerHead.y + playerHead.height > attack.y) {
                
                // 玩家受到伤害
                this.playerTakeDamage(attack.damage);
                
                // 移除攻击对象
                this.boss.attacks.splice(i, 1);
            }
        }
        
        // 检查玩家与BOSS身体的碰撞
        this.checkBossCollision();
        
        // 检查玩家与已放置陷阱的碰撞
        this.checkTrapCollisions();
    }
    
    playerTakeDamage(damage) {
        // 玩家受到伤害
        if (this.gameState.playerHealth > 0) {
            this.gameState.playerHealth -= damage;
            console.log(`玩家受到 ${damage} 点伤害，剩余生命值：${this.gameState.playerHealth}`);
            
            // 更新UI
            this.updateUI();
            
            // 检查玩家是否死亡
            if (this.gameState.playerHealth <= 0) {
                this.gameOver();
            }
        }
    }
    
    checkBossCollision() {
        // 检查玩家与BOSS身体的碰撞
        const playerHead = this.player.body[0];
        const bossHead = this.boss.body[0]; // BOSS头部
        
        // 检查BOSS头部与玩家身体的碰撞（不包括玩家头部）
        for (let i = 1; i < this.player.body.length; i++) {
            const playerSegment = this.player.body[i];
            
            if (bossHead.x < playerSegment.x + playerSegment.width &&
                bossHead.x + bossHead.width > playerSegment.x &&
                bossHead.y < playerSegment.y + playerSegment.height &&
                bossHead.y + bossHead.height > playerSegment.y) {
                
                // 检查冷却时间（1秒）
                const currentTime = Date.now();
                if (currentTime - this.boss.lastHeadCollisionTime >= 1000) {
                    // BOSS头部碰到玩家身体，BOSS受到100点伤害
                    this.bossTakeDamage(100); // BOSS受到100点伤害
                    this.boss.lastHeadCollisionTime = currentTime; // 更新碰撞时间
                    this.showStatusMessage('BOSS头部碰到玩家身体！BOSS受到100点伤害');
                    console.log('BOSS头部碰到玩家身体，BOSS扣血100点，冷却时间开始');
                }
                break;
            }
        }
        
        // 检查玩家与BOSS身体的碰撞（原有逻辑保持不变）
        for (const segment of this.boss.body) {
            if (playerHead.x < segment.x + segment.width &&
                playerHead.x + playerHead.width > segment.x &&
                playerHead.y < segment.y + segment.height &&
                playerHead.y + playerHead.height > segment.y) {
                
                // 玩家碰到BOSS身体，受到伤害
                this.playerTakeDamage(10); // 基础碰撞伤害
                break;
            }
        }
    }
    
    checkTrapCollisions() {
        // 检查玩家与已放置陷阱的碰撞
        if (!this.gameState.placedTraps) return;
        
        const playerHead = this.player.body[0];
        const bossHead = this.boss.body[0];
        
        for (let i = this.gameState.placedTraps.length - 1; i >= 0; i--) {
            const trap = this.gameState.placedTraps[i];
            
            // 检查玩家与陷阱碰撞
            if (playerHead.x < trap.x + trap.width &&
                playerHead.x + playerHead.width > trap.x &&
                playerHead.y < trap.y + trap.height &&
                playerHead.y + playerHead.height > trap.y) {
                
                // 玩家踩到陷阱，受到伤害
                this.playerTakeDamage(15); // 陷阱伤害
                this.showStatusMessage('踩到陷阱！受到15点伤害');
                
                // 移除陷阱
                this.gameState.placedTraps.splice(i, 1);
                console.log('陷阱被触发并移除');
            }
            
            // 检查BOSS与陷阱碰撞
            if (bossHead.x < trap.x + trap.width &&
                bossHead.x + bossHead.width > trap.x &&
                bossHead.y < trap.y + trap.height &&
                bossHead.y + bossHead.height > trap.y) {
                
                // BOSS踩到陷阱，受到伤害
                this.bossTakeDamage(20); // BOSS受到20点伤害
                this.showStatusMessage('BOSS踩到陷阱！受到20点伤害');
                
                // 添加扣血特效
                this.showDamageEffect(bossHead.x + bossHead.width / 2, bossHead.y + bossHead.height / 2, 20);
                
                // 移除陷阱
                this.gameState.placedTraps.splice(i, 1);
                console.log('BOSS踩到陷阱，陷阱被触发并移除');
            }
        }
    }
    
    gameOver() {
        // 游戏结束逻辑
        this.gameState.isRunning = false;
        console.log('游戏结束！玩家被击败！');
        
        // 显示游戏结束信息
        alert('游戏结束！岩石巨蟒击败了你！');
    }
    
    updateAttackStatus() {
        const statusElement = document.getElementById('currentStatus');
        if (statusElement) {
            statusElement.textContent = '攻击中...';
            statusElement.style.color = '#ff6b6b';
            
            // 2秒后恢复
            setTimeout(() => {
                statusElement.textContent = '正常';
                statusElement.style.color = '#4ecdc4';
            }, 2000);
        }
    }
    
    checkBoundaries() {
        const head = this.player.body[0];
        const gridSize = 20; // 网格大小
        
        // 边界检查 - 按照网格系统
        if (head.x < 0) head.x = this.gameWidth - gridSize;
        if (head.x >= this.gameWidth) head.x = 0;
        if (head.y < 0) head.y = this.gameHeight - gridSize;
        if (head.y >= this.gameHeight) head.y = 0;
    }
    
    render() {
        // 清空画布
        this.ctx.fillStyle = '#1a1a2e'; // 改为暗色主题，不要纯黑色
        this.ctx.fillRect(0, 0, this.gameWidth, this.gameHeight);
        
        // 绘制网格背景
        this.drawGrid();
        
        // 绘制食物
        this.drawFood();
        
        // 绘制物品
        this.drawItem();
        
        // 绘制已放置的陷阱
        this.drawPlacedTraps();
        
        // 绘制玩家
        this.drawPlayer();
        
        // 绘制BOSS
        this.drawBoss();
        
        // 绘制BOSS攻击
        this.drawAttacks();
        
        // 绘制游戏信息
        this.drawGameInfo();
        
        // 绘制攻击预警
        this.drawAttackWarnings();
        
        // 绘制扣血特效
        this.drawDamageEffects();
    }
    
    drawGrid() {
        const gridSize = 20;
        this.ctx.strokeStyle = '#4a4a6a'; // 改为更亮的颜色，在暗色背景上可见
        this.ctx.lineWidth = 1; // 增加线宽，使网格更明显
        
        // 垂直线
        for (let x = 0; x <= this.gameWidth; x += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.gameHeight);
            this.ctx.stroke();
        }
        
        // 水平线
        for (let y = 0; y <= this.gameHeight; y += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.gameWidth, y);
            this.ctx.stroke();
        }
    }
    
    drawPlayer() {
        // 绘制身体
        this.player.body.forEach((segment, index) => {
            if (index === 0) {
                // 头部
                this.ctx.fillStyle = '#4ecdc4';
                this.ctx.fillRect(segment.x, segment.y, segment.width, segment.height);
                
                // 头部边框
                this.ctx.strokeStyle = '#fff';
                this.ctx.lineWidth = 2;
                this.ctx.strokeRect(segment.x, segment.y, segment.width, segment.height);
                
                // 眼睛（根据方向）
                this.ctx.fillStyle = '#000';
                const eyeSize = 4;
                switch (this.player.direction) {
                    case 'right':
                        this.ctx.fillRect(segment.x + segment.width - 6, segment.y + 4, eyeSize, eyeSize);
                        this.ctx.fillRect(segment.x + segment.width - 6, segment.y + segment.height - 8, eyeSize, eyeSize);
                        break;
                    case 'left':
                        this.ctx.fillRect(segment.x + 2, segment.y + 4, eyeSize, eyeSize);
                        this.ctx.fillRect(segment.x + 2, segment.y + segment.height - 8, eyeSize, eyeSize);
                        break;
                    case 'up':
                        this.ctx.fillRect(segment.x + 4, segment.y + 2, eyeSize, eyeSize);
                        this.ctx.fillRect(segment.x + segment.width - 8, segment.y + 2, eyeSize, eyeSize);
                        break;
                    case 'down':
                        this.ctx.fillRect(segment.x + 4, segment.y + segment.height - 6, eyeSize, eyeSize);
                        this.ctx.fillRect(segment.x + segment.width - 8, segment.y + segment.height - 6, eyeSize, eyeSize);
                        break;
                }
            } else {
                // 身体
                this.ctx.fillStyle = '#45b7d1';
                this.ctx.fillRect(segment.x, segment.y, segment.width, segment.height);
                
                // 身体边框
                this.ctx.strokeStyle = '#fff';
                this.ctx.lineWidth = 1;
                this.ctx.strokeRect(segment.x, segment.y, segment.width, segment.height);
            }
        });
    }
    
    drawBoss() {
        // 绘制BOSS身体
        this.boss.body.forEach((segment, index) => {
            if (index === 0) {
                // BOSS头部 - 岩石巨蟒
                // 虚弱状态特效：闪烁效果
                if (this.boss.isWeak && Math.floor(Date.now() / 200) % 2 === 0) {
                    this.ctx.fillStyle = '#ff6b6b'; // 虚弱时闪烁为红色
                } else {
                    this.ctx.fillStyle = '#8b4513'; // 正常状态棕色
                }
                this.ctx.fillRect(segment.x, segment.y, segment.width, segment.height);
                
                // 头部边框
                this.ctx.strokeStyle = '#654321';
                this.ctx.lineWidth = 2;
                this.ctx.strokeRect(segment.x, segment.y, segment.width, segment.height);
                
                // 眼睛
                this.ctx.fillStyle = '#ff0000'; // 红色眼睛
                const eyeSize = 6;
                this.ctx.fillRect(segment.x + 8, segment.y + 8, eyeSize, eyeSize);
                this.ctx.fillRect(segment.x + segment.width - 14, segment.y + 8, eyeSize, eyeSize);
                
                // 嘴巴
                this.ctx.strokeStyle = '#ff0000';
                this.ctx.lineWidth = 2;
                this.ctx.beginPath();
                this.ctx.moveTo(segment.x + 10, segment.y + segment.height - 8);
                this.ctx.lineTo(segment.x + segment.width - 10, segment.y + segment.height - 8);
                this.ctx.stroke();
            } else {
                // BOSS身体 - 岩石纹理
                // 虚弱状态特效：闪烁效果
                if (this.boss.isWeak && Math.floor(Date.now() / 200) % 2 === 0) {
                    this.ctx.fillStyle = '#ff8c8c'; // 虚弱时闪烁为浅红色
                } else {
                    this.ctx.fillStyle = '#a0522d'; // 正常状态深棕色
                }
                this.ctx.fillRect(segment.x, segment.y, segment.width, segment.height);
                
                // 身体边框
                this.ctx.strokeStyle = '#8b4513';
                this.ctx.lineWidth = 1;
                this.ctx.strokeRect(segment.x, segment.y, segment.width, segment.height);
                
                // 岩石纹理
                this.ctx.strokeStyle = '#654321';
                this.ctx.lineWidth = 1;
                this.ctx.beginPath();
                this.ctx.moveTo(segment.x + 5, segment.y + 5);
                this.ctx.lineTo(segment.x + 15, segment.y + 15);
                this.ctx.stroke();
                
                this.ctx.beginPath();
                this.ctx.moveTo(segment.x + segment.width - 5, segment.y + 5);
                this.ctx.lineTo(segment.x + segment.width - 15, segment.y + 15);
                this.ctx.stroke();
            }
        });
        
        // 虚弱状态特效：添加红色粒子效果
        if (this.boss.isWeak) {
            this.drawWeakEffect();
        }
        
        // 移除游戏区域内的BOSS血量条，只保留页面中的血量条
    }
    
    drawBossHealthBar() {
        const barWidth = 200;
        const barHeight = 15;
        const barX = (this.gameWidth - barWidth) / 2;
        const barY = 10;
        
        // 背景
        this.ctx.fillStyle = '#333';
        this.ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 血量
        const healthPercent = (this.boss.health / this.boss.maxHealth) * 100;
        const healthWidth = (barWidth * healthPercent) / 100;
        
        // 血量颜色（根据血量变化）
        let healthColor = '#4CAF50'; // 绿色
        if (healthPercent < 30) {
            healthColor = '#f44336'; // 红色
        } else if (healthPercent < 60) {
            healthColor = '#ff9800'; // 橙色
        }
        
        this.ctx.fillStyle = healthColor;
        this.ctx.fillRect(barX, barY, healthWidth, barHeight);
        
        // 边框
        this.ctx.strokeStyle = '#fff';
        this.ctx.lineWidth = 1;
        this.ctx.strokeRect(barX, barY, barWidth, barHeight);
        
        // BOSS名称和血量文本
        this.ctx.fillStyle = '#fff';
        this.ctx.font = '12px Arial';
        this.ctx.fillText(`${this.boss.name} ${Math.round(healthPercent)}%`, barX + 5, barY + 12);
    }
    
    drawAttacks() {
        // 绘制BOSS的攻击对象
        if (!this.boss.attacks) return;
        
        for (const attack of this.boss.attacks) {
            // 根据攻击类型绘制不同的特效
            if (attack.width === 60) { // 巨石攻击
                this.drawBigRockAttack(attack);
            } else { // 普通石头攻击
                this.drawRockAttack(attack);
            }
        }
        
        // 绘制BOSS护盾特效
        this.drawBossShield();
    }
    
    drawRockAttack(attack) {
        // 绘制普通石头攻击
        this.ctx.fillStyle = '#808080'; // 灰色石头
        this.ctx.fillRect(attack.x, attack.y, attack.width, attack.height);
        
        // 石头纹理
        this.ctx.strokeStyle = '#696969';
        this.ctx.lineWidth = 1;
        this.ctx.strokeRect(attack.x, attack.y, attack.width, attack.height);
        
        // 添加石头纹理细节
        this.ctx.strokeStyle = '#a9a9a9';
        this.ctx.beginPath();
        this.ctx.moveTo(attack.x + 5, attack.y + 5);
        this.ctx.lineTo(attack.x + 15, attack.y + 15);
        this.ctx.stroke();
        
        this.ctx.beginPath();
        this.ctx.moveTo(attack.x + attack.width - 5, attack.y + 5);
        this.ctx.lineTo(attack.x + attack.width - 15, attack.y + 15);
        this.ctx.stroke();
        

    }
    
    drawBigRockAttack(attack) {
        // 绘制巨石攻击特效
        
        // 巨石主体
        this.ctx.fillStyle = '#696969'; // 深灰色
        this.ctx.fillRect(attack.x, attack.y, attack.width, attack.height);
        
        // 巨石边框
        this.ctx.strokeStyle = '#808080';
        this.ctx.lineWidth = 3;
        this.ctx.strokeRect(attack.x, attack.y, attack.width, attack.height);
        
        // 巨石裂纹特效
        this.ctx.strokeStyle = '#ff0000';
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.moveTo(attack.x + 10, attack.y + 10);
        this.ctx.lineTo(attack.x + attack.width - 10, attack.y + attack.height - 10);
        this.ctx.stroke();
        
        this.ctx.beginPath();
        this.ctx.moveTo(attack.x + attack.width - 10, attack.y + 10);
        this.ctx.lineTo(attack.x + 10, attack.y + attack.height - 10);
        this.ctx.stroke();
        
        // 巨石发光特效（闪烁）
        if (Math.floor(Date.now() / 200) % 2 === 0) {
            this.ctx.strokeStyle = 'rgba(255, 255, 0, 0.5)';
            this.ctx.lineWidth = 5;
            this.ctx.strokeRect(attack.x - 5, attack.y - 5, attack.width + 10, attack.height + 10);
        }
        
        // 冲击波特效
        this.ctx.strokeStyle = 'rgba(255, 0, 0, 0.3)';
        this.ctx.lineWidth = 10;
        this.ctx.beginPath();
        this.ctx.arc(attack.x + attack.width / 2, attack.y + attack.height / 2, 80, 0, Math.PI * 2);
        this.ctx.stroke();
    }
    
    drawBossShield() {
        // 绘制BOSS护盾特效
        if (!this.boss.shieldActive) return;
        
        const bossCenterX = this.boss.x + this.boss.width / 2;
        const bossCenterY = this.boss.y + this.boss.height / 2;
        
        // 护盾光环（旋转效果）
        const rotation = (Date.now() / 100) % (Math.PI * 2);
        
        this.ctx.strokeStyle = 'rgba(0, 255, 255, 0.7)';
        this.ctx.lineWidth = 5;
        this.ctx.beginPath();
        this.ctx.arc(bossCenterX, bossCenterY, 60, rotation, rotation + Math.PI * 1.5);
        this.ctx.stroke();
        
        // 护盾粒子特效
        for (let i = 0; i < 8; i++) {
            const angle = (i / 8) * Math.PI * 2 + rotation;
            const x = bossCenterX + Math.cos(angle) * 50;
            const y = bossCenterY + Math.sin(angle) * 50;
            
            this.ctx.fillStyle = 'rgba(0, 255, 255, 0.8)';
            this.ctx.beginPath();
            this.ctx.arc(x, y, 3, 0, Math.PI * 2);
            this.ctx.fill();
        }
        
        // 护盾文字
        this.ctx.fillStyle = 'rgba(0, 255, 255, 0.9)';
        this.ctx.font = 'bold 16px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('护盾激活', bossCenterX, bossCenterY - 40);
    }
    
    drawWeakEffect() {
        // 绘制BOSS虚弱状态特效
        const bossCenterX = this.boss.x + this.boss.width / 2;
        const bossCenterY = this.boss.y + this.boss.height / 2;
        
        // 虚弱光环（红色闪烁效果）
        const rotation = (Date.now() / 100) % (Math.PI * 2);
        
        // 红色光环
        this.ctx.strokeStyle = 'rgba(255, 0, 0, 0.7)';
        this.ctx.lineWidth = 4;
        this.ctx.beginPath();
        this.ctx.arc(bossCenterX, bossCenterY, 70, rotation, rotation + Math.PI * 1.5);
        this.ctx.stroke();
        
        // 虚弱粒子特效
        for (let i = 0; i < 12; i++) {
            const angle = (i / 12) * Math.PI * 2 + rotation;
            const x = bossCenterX + Math.cos(angle) * 65;
            const y = bossCenterY + Math.sin(angle) * 65;
            
            // 粒子闪烁效果
            if (Math.floor(Date.now() / 100 + i) % 3 === 0) {
                this.ctx.fillStyle = 'rgba(255, 100, 100, 0.8)';
                this.ctx.beginPath();
                this.ctx.arc(x, y, 4, 0, Math.PI * 2);
                this.ctx.fill();
            }
        }
        
        // 虚弱状态文字
        this.ctx.fillStyle = 'rgba(255, 0, 0, 0.9)';
        this.ctx.font = 'bold 16px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('虚弱状态', bossCenterX, bossCenterY - 50);
    }
    
    drawGameInfo() {
        // 绘制分数
        this.ctx.fillStyle = '#fff';
        this.ctx.font = '16px Arial';
        this.ctx.fillText(`分数: ${this.gameState.score}`, 10, 20);
        
        // 绘制生命值
        this.ctx.fillText(`生命: ${this.gameState.playerHealth}`, 10, 40);
        
        // 绘制长度
        this.ctx.fillText(`长度: ${this.gameState.playerLength}`, 10, 60);
    }
    
    updateUI() {
        // 更新玩家状态
        this.updatePlayerStatus();
        
        // 更新物品栏
        this.updateInventory();
        
        // 更新BOSS血量（后续添加）
        this.updateBossHealth();
    }
    
    updatePlayerStatus() {
        const healthElement = document.getElementById('playerHealth');
        const lengthElement = document.getElementById('playerLength');
        const scoreElement = document.getElementById('playerScore');
        
        if (healthElement) {
            healthElement.textContent = this.gameState.playerHealth;
            
            // 更新血量条
            const healthFill = document.querySelector('.health-fill');
            if (healthFill) {
                healthFill.style.width = `${this.gameState.playerHealth}%`;
            }
        }
        
        if (lengthElement) {
            lengthElement.textContent = this.gameState.playerLength;
        }
        
        if (scoreElement) {
            scoreElement.textContent = this.gameState.score;
        }
    }
    
    updateInventory() {
        const inventorySlots = document.querySelectorAll('.inventory-slot');
        inventorySlots.forEach((slot, index) => {
            const item = this.gameState.inventory[index];
            const slotContent = slot.querySelector('.slot-content');
            
            if (item) {
                slot.classList.add('filled');
                if (slotContent) {
                    slotContent.textContent = item.name || '道具';
                }
            } else {
                slot.classList.remove('filled');
                if (slotContent) {
                    slotContent.textContent = '空';
                }
            }
        });
    }
    
    bossTakeDamage(damage) {
        // BOSS受到伤害
        this.boss.health = Math.max(0, this.boss.health - damage);
        console.log(`BOSS受到${damage}点伤害，剩余血量：${this.boss.health}`);
        
        // 更新BOSS血条
        this.updateBossHealth();
        
        // 检查BOSS是否死亡
        if (this.boss.health <= 0) {
            this.bossDefeated();
        }
    }
    
    showDamageEffect(x, y, damage) {
        // 添加扣血特效
        if (!this.gameState.damageEffects) {
            this.gameState.damageEffects = [];
        }
        
        const damageEffect = {
            x: x,
            y: y,
            text: `-${damage}`,
            startTime: Date.now(),
            duration: 1000, // 1秒
            color: '#ff0000', // 红色
            alpha: 1.0
        };
        
        this.gameState.damageEffects.push(damageEffect);
    }
    
    updateDamageEffects() {
        // 更新扣血特效
        if (!this.gameState.damageEffects) return;
        
        const currentTime = Date.now();
        
        for (let i = this.gameState.damageEffects.length - 1; i >= 0; i--) {
            const effect = this.gameState.damageEffects[i];
            const elapsed = currentTime - effect.startTime;
            const progress = elapsed / effect.duration;
            
            if (progress >= 1) {
                // 特效结束，移除
                this.gameState.damageEffects.splice(i, 1);
            } else {
                // 更新透明度
                effect.alpha = 1.0 - progress;
                // 向上移动
                effect.y -= 0.5;
            }
        }
    }
    
    drawDamageEffects() {
        // 绘制扣血特效
        if (!this.gameState.damageEffects) return;
        
        for (const effect of this.gameState.damageEffects) {
            this.ctx.save();
            this.ctx.globalAlpha = effect.alpha;
            this.ctx.fillStyle = effect.color;
            this.ctx.font = 'bold 16px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText(effect.text, effect.x, effect.y);
            this.ctx.restore();
        }
    }
    
    bossDefeated() {
        // BOSS被击败逻辑
        this.gameState.isRunning = false;
        console.log('BOSS被击败！游戏胜利！');
        
        // 显示胜利信息，2秒后返回BOSS选择页面
        alert('恭喜！你击败了岩石巨蟒！');
        
        // 2秒后自动返回BOSS选择页面
        setTimeout(() => {
            window.location.href = 'boss-choose.html';
        }, 2000);
    }
    
    updateBossHealth() {
        const bossHealthElement = document.querySelector('.boss-health-fill');
        const bossHealthText = document.querySelector('.boss-health-text');
        
        if (bossHealthElement && bossHealthText) {
            const healthPercent = (this.boss.health / this.boss.maxHealth) * 100;
            bossHealthElement.style.width = `${healthPercent}%`;
            bossHealthText.textContent = `${Math.round(healthPercent)}%`;
            
            // 根据血量改变颜色和添加虚弱特效
            if (healthPercent < 30) {
                bossHealthElement.style.backgroundColor = '#f44336'; // 红色
                // BOSS虚弱状态：血量低于30%时添加闪烁特效
                this.boss.isWeak = true;
            } else if (healthPercent < 60) {
                bossHealthElement.style.backgroundColor = '#ff9800'; // 橙色
                this.boss.isWeak = false;
            } else {
                bossHealthElement.style.backgroundColor = '#4CAF50'; // 绿色
                this.boss.isWeak = false;
            }
        }
    }
    
    togglePause() {
        this.gameState.isPaused = !this.gameState.isPaused;
        const pauseMenu = document.getElementById('pauseMenu');
        
        if (pauseMenu) {
            if (this.gameState.isPaused) {
                pauseMenu.classList.remove('hidden');
            } else {
                pauseMenu.classList.add('hidden');
                this.gameLoop(); // 继续游戏循环
            }
        }
    }
    
    restartGame() {
        // 重置游戏状态
        this.gameState = {
            isRunning: true,
            isPaused: false,
            score: 0,
            playerHealth: 100,
            playerLength: 3,
            inventory: [],
            foods: [],
            items: []
        };
        
        // 重置玩家位置
        this.player = {
            x: 400,
            y: 300,
            width: 20,
            height: 20,
            speed: 2, // 修复：使用正确的速度值2，避免速度叠加
            direction: 'right',
            body: []
        };
        
        this.initPlayerBody();
        
        // 隐藏暂停菜单
        const pauseMenu = document.getElementById('pauseMenu');
        if (pauseMenu) {
            pauseMenu.classList.add('hidden');
        }
        
        // 重新开始游戏循环
        this.startGame();
    }
    
    backToMenu() {
        // 返回BOSS选择页面
        window.location.href = 'boss-choose.html';
    }
    
    // 添加物品到物品栏
    addItemToInventory(item) {
        if (this.gameState.inventory.length < 6) {
            this.gameState.inventory.push(item);
            this.updateInventory();
            return true;
        }
        return false;
    }
    
    // 从物品栏移除物品
    removeItemFromInventory(index) {
        if (index >= 0 && index < this.gameState.inventory.length) {
            this.gameState.inventory.splice(index, 1);
            this.updateInventory();
            return true;
        }
        return false;
    }
    
    generateFood() {
        // 限制食物最多同时存在5个
        if (this.gameState.foods.length >= 5) {
            return;
        }
        
        // 生成三种类型的食物
        const foodTypes = [
            { type: 'blue', color: '#4ecdc4', points: 10, growth: 1, heal: 0 }, // 蓝色食物：加长度
            { type: 'red', color: '#ff6b6b', points: 0, growth: 0, heal: 10 },  // 红色食物：回血10
            { type: 'gold', color: '#feca57', points: 30, growth: 3, heal: 0 }   // 金色食物：加更多长度
        ];
        
        const foodType = foodTypes[Math.floor(Math.random() * foodTypes.length)];
        
        const food = {
            x: Math.floor(Math.random() * (this.gameWidth / 20)) * 20,
            y: Math.floor(Math.random() * (this.gameHeight / 20)) * 20,
            width: 20,
            height: 20,
            type: foodType.type,
            color: foodType.color,
            points: foodType.points,
            growth: foodType.growth,
            heal: foodType.heal
        };
        
        this.gameState.foods.push(food);
        console.log('生成食物:', food);
    }
    
    checkFoodCollisions() {
        // 检查玩家与食物的碰撞
        const playerHead = this.player.body[0];
        
        for (let i = this.gameState.foods.length - 1; i >= 0; i--) {
            const food = this.gameState.foods[i];
            
            // 简单的矩形碰撞检测
            if (playerHead.x < food.x + food.width &&
                playerHead.x + playerHead.width > food.x &&
                playerHead.y < food.y + food.height &&
                playerHead.y + playerHead.height > food.y) {
                
                // 玩家吃到食物
                this.consumeFood(food);
                
                // 移除食物
                this.gameState.foods.splice(i, 1);
            }
        }
    }
    
    consumeFood(food) {
        // 增加分数
        this.gameState.score += food.points;
        
        // 增加长度
        this.gameState.playerLength += food.growth;
        
        // 红色食物：回血效果
        if (food.heal > 0) {
            this.gameState.playerHealth = Math.min(100, this.gameState.playerHealth + food.heal);
            console.log(`吃到红色食物，恢复${food.heal}点生命值`);
        }
        
        // 更新UI
        this.updateUI();
        
        console.log(`吃到${food.type}食物，获得${food.points}分，增长${food.growth}长度`);
    }
    
    drawFood() {
        // 绘制食物
        for (const food of this.gameState.foods) {
            this.ctx.fillStyle = food.color;
            this.ctx.fillRect(food.x, food.y, food.width, food.height);
            
            // 添加食物边框
            this.ctx.strokeStyle = '#fff';
            this.ctx.lineWidth = 1;
            this.ctx.strokeRect(food.x, food.y, food.width, food.height);
        }
    }
    
    drawItem() {
        // 绘制物品
        for (const item of this.gameState.items) {
            this.ctx.fillStyle = item.color;
            this.ctx.fillRect(item.x, item.y, item.width, item.height);
            
            // 添加物品边框
            this.ctx.strokeStyle = '#fff';
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(item.x, item.y, item.width, item.height);
            
            // 根据物品类型添加特殊效果
            switch (item.effect) {
                case 'shield':
                    // 护盾物品 - 添加闪烁效果
                    this.ctx.strokeStyle = '#4ecdc4';
                    this.ctx.lineWidth = 3;
                    this.ctx.strokeRect(item.x + 2, item.y + 2, item.width - 4, item.height - 4);
                    break;
                case 'speed':
                    // 加速物品 - 添加箭头效果
                    this.ctx.fillStyle = '#fff';
                    this.ctx.beginPath();
                    this.ctx.moveTo(item.x + item.width / 2, item.y + 5);
                    this.ctx.lineTo(item.x + item.width - 5, item.y + item.height - 5);
                    this.ctx.lineTo(item.x + 5, item.y + item.height - 5);
                    this.ctx.closePath();
                    this.ctx.fill();
                    break;
                case 'slow':
                    // 减速物品 - 添加时钟效果
                    this.ctx.strokeStyle = '#fff';
                    this.ctx.lineWidth = 2;
                    this.ctx.beginPath();
                    this.ctx.arc(item.x + item.width / 2, item.y + item.height / 2, 6, 0, Math.PI * 2);
                    this.ctx.stroke();
                    
                    // 时钟指针
                    this.ctx.beginPath();
                    this.ctx.moveTo(item.x + item.width / 2, item.y + item.height / 2);
                    this.ctx.lineTo(item.x + item.width / 2, item.y + item.height / 2 - 4);
                    this.ctx.stroke();
                    break;
                case 'trap':
                    // 陷阱物品 - 添加闪烁边框和叉号标识
                    this.ctx.strokeStyle = '#ff0000';
                    this.ctx.lineWidth = 3;
                    this.ctx.strokeRect(item.x + 2, item.y + 2, item.width - 4, item.height - 4);
                    
                    // 绘制闪烁的叉号
                    if (Math.floor(Date.now() / 500) % 2 === 0) {
                        this.ctx.strokeStyle = '#ffffff';
                        this.ctx.lineWidth = 2;
                        this.ctx.beginPath();
                        this.ctx.moveTo(item.x + 5, item.y + 5);
                        this.ctx.lineTo(item.x + item.width - 5, item.y + item.height - 5);
                        this.ctx.stroke();
                        
                        this.ctx.beginPath();
                        this.ctx.moveTo(item.x + item.width - 5, item.y + 5);
                        this.ctx.lineTo(item.x + 5, item.y + item.height - 5);
                        this.ctx.stroke();
                    }
                    break;
            }
        }
    }
    
    drawPlacedTraps() {
        // 绘制已放置的陷阱
        if (!this.gameState.placedTraps) return;
        
        for (const trap of this.gameState.placedTraps) {
            // 绘制陷阱主体
            this.ctx.fillStyle = trap.color;
            this.ctx.fillRect(trap.x, trap.y, trap.width, trap.height);
            
            // 绘制陷阱边框
            this.ctx.strokeStyle = '#8B0000'; // 改为深红色边框
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(trap.x, trap.y, trap.width, trap.height);
            
            // 绘制陷阱图标（叉号）
            this.ctx.strokeStyle = '#ffffff';
            this.ctx.lineWidth = 2;
            this.ctx.beginPath();
            this.ctx.moveTo(trap.x + 5, trap.y + 5);
            this.ctx.lineTo(trap.x + trap.width - 5, trap.y + trap.height - 5);
            this.ctx.stroke();
            
            this.ctx.beginPath();
            this.ctx.moveTo(trap.x + trap.width - 5, trap.y + 5);
            this.ctx.lineTo(trap.x + 5, trap.y + trap.height - 5);
            this.ctx.stroke();
            
            // 绘制剩余时间（闪烁效果）
            const remainingTime = trap.duration - (Date.now() - trap.placedTime);
            if (remainingTime > 0) {
                const seconds = Math.ceil(remainingTime / 1000);
                
                // 闪烁效果：最后3秒闪烁
                if (seconds <= 3 && Math.floor(Date.now() / 500) % 2 === 0) {
                    this.ctx.fillStyle = '#ff0000';
                    this.ctx.font = '10px Arial';
                    this.ctx.fillText(seconds.toString(), trap.x + trap.width / 2 - 3, trap.y - 5);
                }
            }
        }
    }
    
    drawAttackWarnings() {
        // 绘制攻击预警
        if (!this.gameState.attackWarnings) return;
        
        for (const warning of this.gameState.attackWarnings) {
            const elapsed = Date.now() - warning.startTime;
            const progress = elapsed / warning.duration;
            
            // 闪烁效果
            if (Math.floor(Date.now() / 200) % 2 === 0) {
                // 绘制全屏红色警告边框
                this.ctx.strokeStyle = '#ff0000';
                this.ctx.lineWidth = 10;
                this.ctx.strokeRect(0, 0, this.gameWidth, this.gameHeight);
                
                // 绘制警告文本
                this.ctx.fillStyle = '#ff0000';
                this.ctx.font = 'bold 24px Arial';
                this.ctx.textAlign = 'center';
                this.ctx.fillText(`警告：${warning.name}`, this.gameWidth / 2, 50);
                
                // 绘制倒计时
                const remaining = Math.ceil((warning.duration - elapsed) / 1000);
                this.ctx.font = 'bold 36px Arial';
                this.ctx.fillText(remaining.toString(), this.gameWidth / 2, 100);
                
                // 绘制BOSS周围的预警光环
                this.ctx.strokeStyle = '#ff0000';
                this.ctx.lineWidth = 5;
                this.ctx.beginPath();
                this.ctx.arc(this.boss.x + this.boss.width / 2, this.boss.y + this.boss.height / 2, 100, 0, Math.PI * 2);
                this.ctx.stroke();
            }
        }
    }
    
    generateItem() {
        // BOSS模式只生成陷阱道具
        const itemType = { name: '陷阱', color: '#4169E1', effect: 'trap', duration: 10000 };
        
        // 检查场上可拾取陷阱数量是否已达上限（3个）
        const currentTrapItems = this.gameState.items.filter(item => item.effect === 'trap');
        if (currentTrapItems.length >= 3) {
            console.log('场上可拾取陷阱已达上限（3个），不再生成新陷阱');
            return;
        }
        
        const item = {
            x: Math.floor(Math.random() * (this.gameWidth / 20)) * 20,
            y: Math.floor(Math.random() * (this.gameHeight / 20)) * 20,
            width: 20,
            height: 20,
            name: itemType.name,
            color: itemType.color,
            effect: itemType.effect,
            duration: itemType.duration,
            isTrap: itemType.effect === 'trap', // 标记是否为陷阱
            placed: false // 是否已放置
        };
        
        this.gameState.items.push(item);
        console.log('生成物品:', item);
    }
    
    checkItemCollisions() {
        // 检查玩家与物品的碰撞
        const playerHead = this.player.body[0];
        
        for (let i = this.gameState.items.length - 1; i >= 0; i--) {
            const item = this.gameState.items[i];
            
            // 简单的矩形碰撞检测
            if (playerHead.x < item.x + item.width &&
                playerHead.x + playerHead.width > item.x &&
                playerHead.y < item.y + item.height &&
                playerHead.y + playerHead.height > item.y) {
                
                // 玩家收集物品
                this.collectItem(item);
                
                // 移除物品
                this.gameState.items.splice(i, 1);
            }
        }
    }
    
    collectItem(item) {
        // 处理物品收集效果
        switch (item.effect) {
            case 'shield':
                this.player.shield = true;
                this.showStatusMessage('获得护盾保护！');
                setTimeout(() => {
                    this.player.shield = false;
                    this.showStatusMessage('护盾保护结束');
                }, item.duration);
                break;
            case 'speed':
                this.player.speed += 1;
                this.showStatusMessage('获得速度提升！');
                setTimeout(() => {
                    this.player.speed -= 1;
                    this.showStatusMessage('速度恢复正常');
                }, item.duration);
                break;
            case 'slow':
                this.boss.speed = Math.max(0.5, this.boss.speed - 0.5);
                this.showStatusMessage('BOSS被减速了！');
                setTimeout(() => {
                    this.boss.speed += 0.5;
                    this.showStatusMessage('BOSS速度恢复正常');
                }, item.duration);
                break;
            case 'trap':
                // 陷阱物品：只添加到物品栏，不立即生效
                this.showStatusMessage('获得陷阱！按F键放置');
                break;
        }
        
        // 添加到物品栏（陷阱物品也需要添加到物品栏）
        if (this.addItemToInventory(item)) {
            console.log(`收集到物品: ${item.name}`);
        } else {
            console.log('物品栏已满，无法添加新物品');
        }
    }
    
    showStatusMessage(message) {
        // 显示状态消息
        const statusElement = document.getElementById('currentStatus');
        if (statusElement) {
            statusElement.textContent = message;
            statusElement.style.color = '#feca57'; // 黄色
            
            // 3秒后恢复默认状态
            setTimeout(() => {
                statusElement.textContent = '正常';
                statusElement.style.color = '#4ecdc4';
            }, 3000);
        }
    }
    
    isColliding(rect1, rect2) {
        // 矩形碰撞检测
        return rect1.x < rect2.x + rect2.width &&
               rect1.x + rect1.width > rect2.x &&
               rect1.y < rect2.y + rect2.height &&
               rect1.y + rect1.height > rect2.y;
    }
    
    getRandomColor() {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
    
    formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    
    adjustGameArea() {
        const gameArea = document.querySelector('.game-canvas-container');
        if (gameArea) {
            const containerWidth = gameArea.clientWidth;
            const containerHeight = gameArea.clientHeight;
            
            // 计算缩放比例
            const scaleX = containerWidth / this.gameWidth;
            const scaleY = containerHeight / this.gameHeight;
            const scale = Math.min(scaleX, scaleY, 1);
            
            this.canvas.style.width = (this.gameWidth * scale) + 'px';
            this.canvas.style.height = (this.gameHeight * scale) + 'px';
        }
    }
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', function() {
    // 创建游戏实例
    window.bossGame = new BossGame();
    
    // 初始调整
    window.bossGame.adjustGameArea();
    
    // 窗口大小变化时调整
    window.addEventListener('resize', () => window.bossGame.adjustGameArea());
});